package com.free4inno.knowledgems.openapi;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Author HUYUZHU.
 * Date 2021/10/24 22:00.
 * 接口返回值统一处理
 */

@ControllerAdvice("com.free4inno.knowledgems.openapi")
public class GlobalReturnConfig implements ResponseBodyAdvice {


    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //TODO 可以通过returnType、converterType获取拦截的方法。返回true将执行beforeBodyWrite()中的操作
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof Result<?>) {
            return body;
        }else {
            return Result.success(body);
        }
    }
}
